//
//  AppDelegate.swift
//  xiaoleservice
//
//  Created by Wenzhe Fan on 2019/6/1.
//  Copyright © 2019年 Wenzhe Fan. All rights reserved.
//

import UIKit
import Alamofire
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        self.setingPush(launchOptions:launchOptions)
        return true
    }
    func setingPush(launchOptions: [UIApplication.LaunchOptionsKey: Any]?){
        let entity = JPUSHRegisterEntity.init()
        entity.types = Int(JPAuthorizationOptions.alert.rawValue | JPAuthorizationOptions.badge.rawValue | JPAuthorizationOptions.sound.rawValue)
        if Float(UIDevice.current.systemVersion) ?? 0.0 >= 8.0 {
        }
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate:(self as! JPUSHRegisterDelegate))
        JPUSHService.setup(withOption: launchOptions, appKey:kJGAppKey, channel: "", apsForProduction: false)
        
    }
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        debugPrint("来自苹果的推送,\(deviceToken)")
        JPUSHService.registerDeviceToken(deviceToken)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        JPUSHService.handleRemoteNotification(userInfo)
        
        let infoDic = userInfo["aps"]  as! [String:Any]
        let message = infoDic["alert"] as! String
        
        let alert = UIAlertController.init(title:nil, message:message , preferredStyle: .alert)
        let sureAct = UIAlertAction.init(title: "确定", style: .default, handler: nil)
        alert.addAction(sureAct)
        UIApplication.shared.applicationIconBadgeNumber = 0
        self.window?.rootViewController?.present(alert, animated: true, completion: nil)
        completionHandler(UIBackgroundFetchResult.newData);
    }

}
@available(iOS 10.0, *)
extension AppDelegate:JPUSHRegisterDelegate{
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification?) {
        if notification != nil && (notification?.request.trigger is UNPushNotificationTrigger) {
            //从通知界面直接进入应用
        } else {
            //从通知设置界面进入应用
        }
    }
    
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        let userInfo = notification.request.content.userInfo
        if notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue | UNNotificationPresentationOptions.sound.rawValue))
    }
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        let userInfo = response.notification.request.content.userInfo
        if response.notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo)
            let infodic = userInfo["aps"]! as! [String:Any]
            debugPrint(infodic)
            let message:String = infodic["alert"] as? String ?? "通知消息"
            let alert = UIAlertController.init(title:nil, message:message , preferredStyle: .alert)
            let sureAct = UIAlertAction.init(title: "确定", style: .default, handler: nil)
            alert.addAction(sureAct)
            UIApplication.shared.applicationIconBadgeNumber = 0
            self.window?.rootViewController?.present(alert, animated: true, completion: nil)
        }
        completionHandler();
    }
    
}
